package org.kos.android.rusoftkeyboard;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.content.res.TypedArray;
import android.util.Xml;
import android.util.Log;

import java.util.Map;
import java.util.HashMap;

import org.xmlpull.v1.XmlPullParser;

public class RawConverter {
    private Map<Integer, Scan> table = new HashMap<Integer, Scan>();

    public RawConverter(final Context context, final int xmlLayoutResId) {
        final Resources resources = context.getResources();
        final XmlResourceParser parser = resources.getXml(xmlLayoutResId);
        try {
            int event;
            while ((event = parser.next()) != XmlPullParser.END_DOCUMENT) {
                if (event == XmlPullParser.START_TAG) {
                    final String tag = parser.getName();
                    if ("Scan".equals(tag)) {
                        final Scan s = new Scan(resources, parser);
                        table.put(s.code, s);
                    }
                }
            }
        } catch (Exception e) {
            Log.e("RawConverter", "error parsing xml: " + e);
            e.printStackTrace();
        }
    }

    public boolean hasMapping(final int scanCode) {
        return table.containsKey(scanCode);
    }

    public int convert(final int scanCode, final boolean alt) {
        final Scan scan = table.get(scanCode);
        if (scan == null) return 0;
        return alt ? scan.alt : scan.mapto;
    }

    private static class Scan {
        final int code, mapto, alt;

        public Scan(final Resources res, final XmlResourceParser parser) {
            final TypedArray typedArray = res.obtainAttributes(Xml.asAttributeSet(parser), R.styleable.Scan);
            code = typedArray.getInteger(R.styleable.Scan_code, 0);
            mapto = typedArray.getInteger(R.styleable.Scan_mapto, 0);
            alt = typedArray.getInteger(R.styleable.Scan_alt, mapto);
            //Log.i("RawConverter", "loaded Scan: " + code + "->(" + mapto + "," + alt + ")");
        }
    }
}
